package com.yunyao.dao.service.bamu.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunyao.common.constant.enums.DataDeletedStatus;
import com.yunyao.common.constant.enums.OrderStatus;
import com.yunyao.common.core.BaseContext;
import com.yunyao.common.dto.order.ProjectOrderDto;
import com.yunyao.common.web.util.StringUtils;
import com.yunyao.dao.mapper.BamuPurchaseApplyMapper;
import com.yunyao.dao.model.BamuPurchaseApply;
import com.yunyao.dao.service.bamu.IBamuPurchaseApplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotBlank;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 项目订单、采购订单 服务实现类
 * </p>
 *
 * @author 陈叶剑
 * @since 2024-07-02
 */
@Service
public class BamuPurchaseApplyServiceImpl extends ServiceImpl<BamuPurchaseApplyMapper, BamuPurchaseApply> implements IBamuPurchaseApplyService {
    @Autowired
    private BamuPurchaseApplyMapper purchaseMappingMapper;

    /**
     * 获取采购申请列表
     * <p>
     * 本方法通过调用数据库操作接口获取采购申请的分页列表，用于展示或进一步处理
     * 它实现了从数据库中检索与特定项目订单相关的采购申请信息的功能
     *
     * @param projectOrderDto 项目订单数据传输对象，包含查询条件等信息
     * @return 返回采购申请列表，供调用者进一步使用或展示
     */
    @Override
    public IPage<BamuPurchaseApply> getPurchaseApplyList(ProjectOrderDto projectOrderDto) {
        // 查询满足条件的总页数
        if (StringUtils.isNotEmpty(projectOrderDto.getAuditStatus())) {
            String auditStateDescription = OrderStatus.getDescriptionByType(projectOrderDto.getAuditStatus());
            String auditStateString = OrderStatus.getTypeStringByDesc(auditStateDescription);
            projectOrderDto.setAuditStatus(auditStateString);
        }
        projectOrderDto.setProjectIds(BaseContext.getProjectList());
        projectOrderDto.setTenantId(BaseContext.getUserInfo().getTenantId());
        long pageCount = purchaseMappingMapper.pageCount(projectOrderDto);
        // 创建并设置分页对象的属性
        IPage<BamuPurchaseApply> page = new Page<>(projectOrderDto.getPageIndex(), projectOrderDto.getPageSize(), pageCount);
        // 如果总页数为0，则直接返回空的分页对象
        if (pageCount == 0) {
            return page;
        }
        // 计算当前页码对应的数据起始索引
        long index = projectOrderDto.getPageIndex() <= 1 ? 0 : (projectOrderDto.getPageIndex() - 1) * projectOrderDto.getPageSize();
        projectOrderDto.setPageIndex(index);
        // 根据起始索引和每页显示数量获取分页材料列表
        List<BamuPurchaseApply> pageList = purchaseMappingMapper.getPurchaseApplyPageList(projectOrderDto);
        page.setRecords(pageList);
        // 计算总页数并设置
        page.setPages(pageCount % projectOrderDto.getPageSize() == 0 ? pageCount / projectOrderDto.getPageSize() : pageCount / projectOrderDto.getPageSize() + 1);
        return page;
    }

    /**
     * 根据ID获取未删除的采购申请
     * 此方法旨在通过ID检索采购申请记录，特别强调未被逻辑删除的记录
     * 它提供了一种筛选机制，确保只检索处于使用中的采购申请
     *
     * @param id 采购申请的唯一标识符如果ID为空或null，则返回null，表示找不到指定的采购申请
     * @return 返回找到的采购申请对象，如果找不到或ID无效，则返回null
     */
    @Override
    public BamuPurchaseApply getNoDeletedApplyById(String id) {
        // 检查ID是否为空或null，如果是，则返回null
        if (StringUtils.isEmpty(id)) {
            return null;
        }
        // 创建一个LambdaQueryWrapper实例，用于构建查询条件
        LambdaQueryWrapper<BamuPurchaseApply> wrapper = new LambdaQueryWrapper<>();
        // 向查询条件中添加ID和未删除状态的条件
        wrapper.eq(BamuPurchaseApply::getId, id)
                .eq(BamuPurchaseApply::getIsDeleted, DataDeletedStatus.NO.getType());
        // 使用构建的查询条件查询并返回对应的采购申请对象
        return getOne(wrapper);
    }

    @Override
    public List<BamuPurchaseApply> listByReconciliationSettlementIdDeleted(String contractId) {
        // 检查对账ID列表是否为空，如果为空则直接返回空列表
        if (org.apache.commons.lang3.StringUtils.isBlank(contractId)) {
            return List.of();
        }

        // 创建查询条件封装Lambda表达式，用于筛选特定条件的对账结算单
        LambdaQueryWrapper<BamuPurchaseApply> wrapper =
                new LambdaQueryWrapper<BamuPurchaseApply>()
                        // 条件1：对账ID在给定的列表中
                        .in(BamuPurchaseApply::getContractId,
                                contractId)
                        // 条件2：对账结算单的删除状态为未删除
                        .eq(BamuPurchaseApply::getIsDeleted,
                                DataDeletedStatus.NO.getType());
        return list(wrapper);
    }

    @Override
    public BigDecimal getTotalPriceByContractId(String contractId) {
        return purchaseMappingMapper.getSumTaxTotalPriceByContractId(contractId);
    }

//    @Override
//    public BamuPurchaseApply getBySupplyApplyId(String id) {
//        LambdaQueryWrapper<BamuPurchaseApply> wrapper = new LambdaQueryWrapper<>();
//        return null;
//    }

    @Override
    public List<BamuPurchaseApply> listById(String Id) {
        // 检查合同ID是否为空或空白，如果是，则返回一个空列表
        if (org.apache.commons.lang3.StringUtils.isBlank(Id)) {
            return List.of();
        }
        // 创建一个LambdaQueryWrapper用于构建查询条件
        LambdaQueryWrapper<BamuPurchaseApply> wrapper =
                new LambdaQueryWrapper<BamuPurchaseApply>().eq(BamuPurchaseApply::getId,
                        Id).eq(BamuPurchaseApply::getIsDeleted, DataDeletedStatus.NO.getType());
        // 使用构建的查询条件获取并返回关联的材料列表
        return list(wrapper);
    }

    @Override
    public BamuPurchaseApply getOderId(@NotBlank String orderNo, @NotBlank String contractId) {
        return lambdaQuery()
                .eq(BamuPurchaseApply::getOrderSn, orderNo)
                .eq(BamuPurchaseApply::getContractId, contractId)
                .eq(BamuPurchaseApply::getIsDeleted, 0)
                .one();
    }

}
